import { ref } from 'vue'

/**
 * 文本处理功能组合式函数
 */
export function useTextProcessor() {
  const isProcessing = ref(false)

  // 数字处理功能
  const increment = (str: string): string => {
    return str.replace(/\d+/g, (match) => {
      return (parseInt(match, 10) + 1).toString()
    })
  }

  const decrement = (str: string): string => {
    return str.replace(/\d+/g, (match) => {
      return (parseInt(match, 10) - 1).toString()
    })
  }

  const createSequence = (str: string): string => {
    const lines = str.split('\n')
    let counter = 0
    
    return lines.map(line => {
      return line.replace(/\d+/, () => {
        return (counter++).toString()
      })
    }).join('\n')
  }

  // 排序功能
  const sortAsc = (str: string): string => {
    const lines = str.split('\n')
    return lines.sort((a, b) => a.localeCompare(b)).join('\n')
  }

  const sortDesc = (str: string): string => {
    const lines = str.split('\n')
    return lines.sort((a, b) => b.localeCompare(a)).join('\n')
  }

  const sortLength = (str: string): string => {
    const lines = str.split('\n')
    return lines.sort((a, b) => a.length - b.length).join('\n')
  }

  const shuffle = (str: string): string => {
    const lines = str.split('\n')
    for (let i = lines.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1))
      ;[lines[i], lines[j]] = [lines[j], lines[i]]
    }
    return lines.join('\n')
  }

  const reverse = (str: string): string => {
    const lines = str.split('\n')
    return lines.reverse().join('\n')
  }

  const sortJson = (str: string): string => {
    try {
      const obj = JSON.parse(str)
      const sortedObj = sortObjectKeys(obj)
      return JSON.stringify(sortedObj, null, 2)
    } catch (error) {
      throw new Error('无效的JSON格式')
    }
  }

  const sortObjectKeys = (obj: any): any => {
    if (Array.isArray(obj)) {
      return obj.map(sortObjectKeys)
    } else if (obj !== null && typeof obj === 'object') {
      const sortedKeys = Object.keys(obj).sort()
      const sortedObj: any = {}
      sortedKeys.forEach(key => {
        sortedObj[key] = sortObjectKeys(obj[key])
      })
      return sortedObj
    }
    return obj
  }

  // 对齐功能
  const alignLeft = (str: string): string => {
    const lines = str.split('\n')
    return lines.map(line => line.trimStart()).join('\n')
  }

  const alignCenter = (str: string): string => {
    const lines = str.split('\n')
    const maxLength = Math.max(...lines.map(line => line.trim().length))
    
    return lines.map(line => {
      const trimmed = line.trim()
      const padding = Math.max(0, maxLength - trimmed.length)
      const leftPadding = Math.floor(padding / 2)
      return ' '.repeat(leftPadding) + trimmed
    }).join('\n')
  }

  const alignRight = (str: string): string => {
    const lines = str.split('\n')
    const maxLength = Math.max(...lines.map(line => line.trim().length))
    
    return lines.map(line => {
      const trimmed = line.trim()
      const padding = Math.max(0, maxLength - trimmed.length)
      return ' '.repeat(padding) + trimmed
    }).join('\n')
  }

  // 过滤/清理功能
  const removeDuplicates = (str: string): string => {
    const lines = str.split('\n')
    const uniqueLines = [...new Set(lines)]
    return uniqueLines.join('\n')
  }

  const removeEmptyLines = (str: string): string => {
    const lines = str.split('\n')
    return lines.filter(line => line.trim() !== '').join('\n')
  }

  const trimSpaces = (str: string): string => {
    const lines = str.split('\n')
    return lines.map(line => line.trim()).join('\n')
  }

  const removeAllSpaces = (str: string): string => {
    return str.replace(/\s/g, '')
  }

  const compressSpaces = (str: string): string => {
    return str.replace(/\s+/g, ' ').trim()
  }

  // 其他操作
  const reverseText = (str: string): string => {
    return str.split('').reverse().join('')
  }

  const swapQuotes = (str: string): string => {
    const singleToDouble = str.replace(/'/g, '"')
    const doubleToSingle = str.replace(/"/g, "'")
    
    // 简单的交换逻辑：如果原文本主要包含单引号，则转为双引号，反之亦然
    const singleCount = (str.match(/'/g) || []).length
    const doubleCount = (str.match(/"/g) || []).length
    
    if (singleCount > doubleCount) {
      return singleToDouble
    } else {
      return doubleToSingle
    }
  }

  const removeLineBreaks = (str: string): string => {
    return str.replace(/\r?\n/g, ' ').replace(/\s+/g, ' ').trim()
  }

  // 处理函数映射
  const processors: Record<string, (str: string) => string> = {
    // 数字处理
    increment,
    decrement,
    createSequence,
    
    // 排序
    sortAsc,
    sortDesc,
    sortLength,
    shuffle,
    reverse,
    sortJson,
    
    // 对齐
    alignLeft,
    alignCenter,
    alignRight,
    
    // 过滤/清理
    removeDuplicates,
    removeEmptyLines,
    trimSpaces,
    removeAllSpaces,
    compressSpaces,
    
    // 其他操作
    reverseText,
    swapQuotes,
    removeLineBreaks
  }

  // 主处理函数
  const process = (type: string, text: string): string => {
    if (!text) return ''
    
    isProcessing.value = true
    
    try {
      const processor = processors[type]
      if (!processor) {
        throw new Error(`未知的处理类型: ${type}`)
      }
      
      return processor(text)
    } catch (error) {
      throw error
    } finally {
      isProcessing.value = false
    }
  }

  return {
    process,
    isProcessing
  }
}